<?php

namespace app\task\cron\mobile;

use yunwuxin\cron\Task;
use think\facade\Db;

/**
 * 删除过期的话费成功率统计数据【30分钟】
 */
class DeleteExpireStatsData extends Task
{
    /**
     * 10分钟执行1次
     */
    protected function configure()
    {
        // 分 时 日 月 周
        $this->expression = '*/10 * * * *';
    }

    /**
     * 执行指令.
     */
    protected function handle()
    {
        $lockKey = 'mobile_order_stat.delete_expire_data';
        echo 'start' . PHP_EOL;
        $lockVal = cache($lockKey);
        if ($lockVal) {
            echo '还在处理呢' . PHP_EOL;

            return true;
        }

        cache($lockKey, 1, 500);

        $table = 'mobile_order_stats';
        $where = [
            ['created_at', '<', date('Y-m-d H:i:s', time() - 31 * 60)]
        ];
        $count = Db::name($table)
            ->where($where)
            ->count();
        $deleteCountPerTime = 500; // 单次删除条数
        $times = ceil($count / $deleteCountPerTime);
        for ($i = 0; $i < $times; $i++) {
            Db::name($table)
                ->where($where)
                ->limit($deleteCountPerTime)
                ->delete();
        }

        cache($lockKey, null);
        echo 'ok' . PHP_EOL;
    }
}
